// 游戏设置
const GRID_SIZE = 20;
const CELL_SIZE = 20;
const GAME_WIDTH = 400;
const GAME_HEIGHT = 400;

// 初始化游戏
let snake = [{x: 10, y: 10}];
let food = generateFood();
let direction = {x: 0, y: 0};
let gameSpeed = 200;
let gameInterval;

// 获取游戏区域
const gameArea = document.getElementById('game');

// 生成食物
function generateFood() {
  return {
    x: Math.floor(Math.random() * (GAME_WIDTH / CELL_SIZE)),
    y: Math.floor(Math.random() * (GAME_HEIGHT / CELL_SIZE))
  };
}

// 绘制游戏元素
function draw() {
  gameArea.innerHTML = '';
  // 绘制蛇
  snake.forEach(segment => {
    const snakeElement = document.createElement('div');
    snakeElement.style.left = `${segment.x * CELL_SIZE}px`;
    snakeElement.style.top = `${segment.y * CELL_SIZE}px`;
    snakeElement.classList.add('snake');
    gameArea.appendChild(snakeElement);
  });

  // 绘制食物
  const foodElement = document.createElement('div');
  foodElement.style.left = `${food.x * CELL_SIZE}px`;
  foodElement.style.top = `${food.y * CELL_SIZE}px`;
  foodElement.classList.add('food');
  gameArea.appendChild(foodElement);
}

// 更新游戏状态
function update() {
  const head = {x: snake[0].x + direction.x, y: snake[0].y + direction.y};

  // 碰撞检测
  if (head.x < 0 || head.x >= GAME_WIDTH / CELL_SIZE ||
      head.y < 0 || head.y >= GAME_HEIGHT / CELL_SIZE ||
      snake.some(segment => segment.x === head.x && segment.y === head.y)) {
    clearInterval(gameInterval);
    alert('游戏结束!');
    return;
  }

  snake.unshift(head);
  if (head.x === food.x && head.y === food.y) {
    food = generateFood();
  } else {
    snake.pop();
  }
}

// 游戏循环
function gameLoop() {
  update();
  draw();
}

// 开始游戏
function startGame() {
  gameInterval = setInterval(gameLoop, gameSpeed);
}

// 处理键盘输入
window.addEventListener('keydown', e => {
  switch (e.key) {
    case 'ArrowUp':
      if (direction.y === 0) direction = {x: 0, y: -1};
      break;
    case 'ArrowDown':
      if (direction.y === 0) direction = {x: 0, y: 1};
      break;
    case 'ArrowLeft':
      if (direction.x === 0) direction = {x: -1, y: 0};
      break;
    case 'ArrowRight':
      if (direction.x === 0) direction = {x: 1, y: 0};
      break;
  }
});

// 启动游戏
startGame();